<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '修改SKU' : '新增SKU' }}</span>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品" prop="productId">
              <id-selector
                v-model="form.productId"
                placeholder="请选择商品"
                dialog-title="选择商品"
                :api-function="listProduct"
                :get-api-function="getProduct"
                id-field="productId"
                name-field="productName"
                id-label="商品ID"
                name-label="商品名称"
                search-label="商品名称"
                search-placeholder="请输入商品名称"
                :extra-columns="[{prop: 'productCode', label: '商品编码'}, {prop: 'price', label: '价格'}]"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="SKU编码" prop="skuCode">
              <coding-input
                v-model="form.skuCode"
                table-name="fun_sku"
                field-name="sku_code"
                :is-edit="isEdit"
                :enable-auto-generate="true"
                :show-preview="true"
                :show-refresh="true"
                placeholder="请输入SKU编码或点击生成"
                @code-generated="handleCodeGenerated"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入价格" type="number" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="原价" prop="originalPrice">
              <el-input v-model="form.originalPrice" placeholder="请输入原价" type="number" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="成本价" prop="costPrice">
              <el-input v-model="form.costPrice" placeholder="请输入成本价" type="number" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="库存数量" prop="stock">
              <el-input v-model="form.stock" placeholder="库存数量（通过库存导入设置）" type="number" :disabled="true" />
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="库存预警值" prop="lowStock">
              <el-input v-model="form.lowStock" placeholder="请输入库存预警值" type="number" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="重量" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入重量" type="number" />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="20">
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="体积" prop="volume">
              <el-input v-model="form.volume" placeholder="请输入体积" type="number" />
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="销量" prop="saleCount">
              <el-input v-model="form.saleCount" placeholder="销量由系统自动统计" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="SKU名称" prop="skuName">
              <el-input v-model="form.skuName" placeholder="请输入SKU名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="规格信息" prop="specInfo">
              <div class="spec-info-container">
                <div v-for="(spec, index) in specList" :key="index" class="spec-item">
                  <el-input
                    v-model="spec.key"
                    placeholder="规格名称（如：颜色）"
                    style="width: 200px; margin-right: 10px;"
                  />
                  <span class="colon">:</span>
                  <el-input
                    v-model="spec.value"
                    placeholder="规格值（如：红色）"
                    style="width: 200px; margin-left: 10px; margin-right: 10px;"
                  />
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="removeSpec(index)"
                    :disabled="specList.length === 1"
                  ></el-button>
                </div>
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="addSpec"
                  style="margin-top: 10px;"
                >添加规格</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="SKU图片" prop="image">
              <image-upload v-model="form.image"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="会员专享" prop="isVipBuy">
              <el-radio-group v-model="form.isVipBuy">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="16" :lg="18" :xl="18">
            <el-form-item label="购买白名单" prop="buyWhiteList">
              <div style="display: flex; align-items: flex-start; gap: 10px;">
                <id-selector
                  v-model="buyWhiteListIds"
                  placeholder="请选择购买白名单用户"
                  dialog-title="选择用户"
                  :api-function="listUser"
                  :get-api-function="getUser"
                  id-field="userId"
                  name-field="userName"
                  id-label="用户ID"
                  name-label="用户名称"
                  search-label="用户名称"
                  search-placeholder="请输入用户名称"
                  :extra-columns="[{prop: 'nickName', label: '用户昵称'}, {prop: 'email', label: '邮箱'}]"
                  :multiple="true"
                  @change="handleBuyWhiteListChange"
                  style="flex: 1;"
                />
                <el-button 
                  type="danger" 
                  size="small" 
                  icon="el-icon-delete" 
                  @click="clearBuyWhiteListSelection"
                  title="清空选择"
                >
                  清空
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item style="text-align: center; margin-top: 30px;">
          <el-button type="primary" @click="submitForm" :loading="loading">{{ isEdit ? '修改' : '新增' }}</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getSku, addSku, updateSku } from "@/api/fun/sku"
import { listProduct, getProduct } from "@/api/fun/product"
import { listUser, getUser } from "@/api/system/user"
import IdSelector from "@/components/IdSelector"
import CodingInput from '@/components/CodingInput'

export default {
  name: "SkuForm",
  components: {
    IdSelector,
    CodingInput
  },
  dicts: ['sys_common_status'],
  data() {
    return {
      // 提交状态
      loading: false,
      // 是否为编辑模式
      isEdit: false,
      // 规格信息列表
      specList: [
        { key: '', value: '' }
      ],
      // 购买白名单用户ID数组
      buyWhiteListIds: [],
      // 表单参数
      form: {
        skuId: null,
        productId: null,
        skuCode: null,
        skuName: null,
        specInfo: null,
        price: null,
        originalPrice: null,
        costPrice: null,
        stock: 0,
        lowStock: 0,
        weight: null,
        volume: null,
        image: null,
        saleCount: 0,
        status: "0",
        isVipBuy: 0,
        buyWhiteList: null
      },
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "商品ID不能为空", trigger: "blur" }
        ],
        skuCode: [
          { required: true, message: "SKU编码不能为空", trigger: "blur" }
        ],
        skuName: [
          { required: true, message: "SKU名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "库存数量不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    const pageType = this.$route.query.pageType
    const skuId = this.$route.query.skuId
    const productId = this.$route.query.productId
    const copyData = this.$route.query.copyData

    // 如果是新增且有productId参数，自动填入表单
    if (pageType === 'add' && productId) {
      this.form.productId = productId
    }

    // 如果是复制新增，处理复制数据
    if (pageType === 'add' && copyData) {
      try {
        const decodedData = JSON.parse(decodeURIComponent(atob(copyData)))
        // 将复制的数据填入表单，但排除skuId和skuCode
        Object.keys(decodedData).forEach(key => {
          if (key !== 'skuId' && key !== 'skuCode') {
            this.form[key] = decodedData[key]
          }
        })
        // 解析规格信息
        if (decodedData.specInfo) {
          this.parseSpecInfo(decodedData.specInfo)
        }
      } catch (error) {
        console.error('解析复制数据失败:', error)
        this.$modal.msgError('复制数据格式错误')
      }
    }

    if (pageType === 'edit' && skuId) {
      this.isEdit = true
      this.getSkuInfo(skuId)
    }
  },
  methods: {
    /** 获取SKU详细信息 */
    getSkuInfo(skuId) {
      getSku(skuId).then(response => {
        this.form = response.data
        // 解析规格信息
        this.parseSpecInfo(this.form.specInfo)
        // 解析购买白名单
        this.parseBuyWhiteList(this.form.buyWhiteList)
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        skuId: null,
        productId: null,
        skuCode: null,
        skuName: null,
        specInfo: null,
        price: null,
        originalPrice: null,
        costPrice: null,
        stock: null,
        lowStock: 0,
        weight: null,
        volume: null,
        image: null,
        saleCount: 0,
        status: "0",
        isVipBuy: 0,
        buyWhiteList: null
      }
      this.specList = [{ key: '', value: '' }]
      this.buyWhiteListIds = []
      this.resetForm("form")
    },
    /** 取消按钮 */
    cancel() {
      this.$tab.closePage()
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          // 确保销量字段为0（由系统自动统计）
          this.form.saleCount = 0
          // 将规格信息转换为JSON字符串
          this.form.specInfo = this.buildSpecInfo()
          // 将购买白名单ID数组转换为逗号分隔的字符串
          this.form.buyWhiteList = this.buildBuyWhiteList()
          if (this.form.skuId != null) {
            updateSku(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              // 通知父页面刷新列表
              this.$eventBus.$emit('refreshSkuList')
              this.$tab.closePage()
            }).finally(() => {
              this.loading = false
            })
          } else {
            addSku(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              // 通知父页面刷新列表
              this.$eventBus.$emit('refreshSkuList')
              this.$tab.closePage()
            }).finally(() => {
              this.loading = false
            })
          }
        }
      })
    },
    /** 编码生成回调 */
    handleCodeGenerated(code) {
      console.log('生成的SKU编码:', code)
      // 可以在这里处理编码生成后的逻辑
    },
    /** 添加规格 */
    addSpec() {
      this.specList.push({ key: '', value: '' })
    },
    /** 删除规格 */
    removeSpec(index) {
      if (this.specList.length > 1) {
        this.specList.splice(index, 1)
      }
    },
    /** 解析规格信息 */
    parseSpecInfo(specInfo) {
      if (!specInfo) {
        this.specList = [{ key: '', value: '' }]
        return
      }
      try {
        const specs = JSON.parse(specInfo)
        this.specList = Object.keys(specs).map(key => ({
          key: key,
          value: specs[key]
        }))
        if (this.specList.length === 0) {
          this.specList = [{ key: '', value: '' }]
        }
      } catch (e) {
        // 如果不是JSON格式，尝试解析旧格式（颜色:红色,尺寸:L）
        const pairs = specInfo.split(',')
        this.specList = pairs.map(pair => {
          const [key, value] = pair.split(':')
          return {
            key: key ? key.trim() : '',
            value: value ? value.trim() : ''
          }
        }).filter(spec => spec.key || spec.value)
        if (this.specList.length === 0) {
          this.specList = [{ key: '', value: '' }]
        }
      }
    },
    /** 构建规格信息JSON字符串 */
    buildSpecInfo() {
      const specs = {}
      this.specList.forEach(spec => {
        if (spec.key && spec.value) {
          specs[spec.key.trim()] = spec.value.trim()
        }
      })
      return Object.keys(specs).length > 0 ? JSON.stringify(specs) : null
    },
    /** 解析购买白名单 */
    parseBuyWhiteList(buyWhiteList) {
      if (!buyWhiteList) {
        this.buyWhiteListIds = []
        return
      }
      // 将逗号分隔的字符串转换为数组
      this.buyWhiteListIds = buyWhiteList.split(',').filter(id => id.trim()).map(id => parseInt(id.trim()))
    },
    /** 构建购买白名单字符串 */
    buildBuyWhiteList() {
      if (!this.buyWhiteListIds || this.buyWhiteListIds.length === 0) {
        return ''
      }
      return this.buyWhiteListIds.join(',')
    },
    /** 购买白名单选择变化 */
    handleBuyWhiteListChange(selectedIds) {
      this.buyWhiteListIds = selectedIds
    },
    /** 清空购买白名单选择 */
    clearBuyWhiteListSelection() {
      this.buyWhiteListIds = []
    },
    // API方法
    listProduct,
    getProduct,
    listUser,
    getUser
  }
}
</script>

<style scoped>
.spec-info-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.spec-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.spec-item:last-child {
  margin-bottom: 0;
}

.colon {
  font-weight: bold;
  font-size: 16px;
  color: #606266;
  margin: 0 5px;
}

.spec-item .el-input {
  flex-shrink: 0;
}

.spec-item .el-button {
  flex-shrink: 0;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
</style>
